package com.jandan.web;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;
import org.springframework.web.util.WebUtils;

import com.jandan.logic.JWordzFacade;
import com.jandan.ui.model.CnAndSentence;
import com.jandan.ui.model.Word;
import com.jandan.ui.server.DataMock;
import com.jandan.web.front.UserSession;
/**
 * 
 * 用于处理获取获取陌生单词的ajax请求，返回json格式数据，请求路径在json-servlet.xml中配置，关于所使用的json处理包，参见相关文档
 * 这个类用于单词学习的客户端，可以不用管先
 * @author Gong Yong
 * @version 1.0
 *
 */
public class StrangeWordBrowserController implements Controller {
	private JWordzFacade jwordz;

	public void setJwordz(JWordzFacade jwordz) {
		this.jwordz = jwordz;
	}
	
	public ModelAndView handleRequest(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		// TODO Auto-generated method stub
//		String wordLibID = request.getParameter("wordLibID");
		UserSession userSession = (UserSession) WebUtils.getSessionAttribute(request, "userSession");
		if(userSession == null){
			return null;
		}
		
		long userID = userSession.getAccount().getUserID();
		int start = Integer.parseInt(request.getParameter("start"));
		int limit = Integer.parseInt(request.getParameter("limit"));

		List<Word> words = jwordz.getStrangeWordListByUserID(userID,start,limit);
		int count = jwordz.getStrangeWordCountByUserID(userID);

		Map model = new HashMap();
		model.put("totalCount", count);
		ArrayList list = new ArrayList();

		Iterator<Word> it = words.iterator();
		Map map = null;
		StringBuffer wordCn = null;
		StringBuffer details = null;
		List<CnAndSentence> csList = null;
		int n = 0;
		CnAndSentence cs = null;
		String c = null;
		String s = null;
		while (it.hasNext()) {
			Word word = it.next();
			map = new HashMap();
			map.put("wordID", word.getWordID());
			map.put("wordEn", word.getWordEn());
			map.put("phonetics", word.getPhonetics());
			wordCn = new StringBuffer();
			details = new StringBuffer();
			csList = word.getCnAndSentenceList();
			n = csList.size();
			for (int i = 0; i < n; i++) {
				cs = csList.get(i);
				if (cs != null) {
					wordCn.append(cs.getCn());
					wordCn.append(";");
					c = cs.getCn();
					s = cs.getSentence();
					if (s != null && s.trim().length() > 0
							&& !s.trim().equalsIgnoreCase("none")) {
						details.append(c);
						details.append("|");
						details.append(s);
						details.append(i != n - 1 ? "|" : "");
					}
				}
			}
			map.put("wordCn", wordCn.toString());
			map.put("details", details.toString());
			list.add(map);
		}
		model.put("words", list);
		return new ModelAndView("jsonView", model);
	}
}
